<template>
  <div class="home container">
    <HeroBanner :ads="ads" @scroll-search="scrollToSearch" @view-solutions="scrollToWorkflow" />
    <SearchFilters
      v-model="filters"
      :brands="brandOptions"
      :origins="originOptions"
      :warehouses="warehouseOptions"
      @search="handleSearch"
      @reset="handleReset"
    />
    <ProductList
      :products="products"
      :is-logged-in="isLoggedIn"
      :loading="catalogLoading"
      :error="catalogError"
      :page="pagination.page"
      :page-size="pagination.pageSize"
      :total="catalogTotal"
      @login-required="openLogin"
      @verify-stock="handleVerifyStock"
      @add-cart="handleAddToCart"
      @reset-search="handleReset"
      @request-verification-info="scrollToWorkflow"
      @retry="handleRetry"
      @change-page="handlePageChange"
    />
    <section class="home__member-preview card">
      <div class="home__preview-header">
        <h2>会员中心 · 企业协同总览</h2>
        <p>
          采购、财务、运营多角色协同，覆盖核实、下单、结算全链路。登录后可访问会员中心、购物车、核实记录与订单追踪。
        </p>
      </div>
      <div class="home__preview-grid">
        <article class="preview-card">
          <h3>交易协同</h3>
          <ul>
            <li>库存核实 → 下单 → 支付 → 物流签收全程跟踪</li>
            <li>支持采购单批量导入、批次追溯与异常提醒</li>
            <li>企业订单按项目、仓库、状态维度智能分类</li>
          </ul>
        </article>
        <article class="preview-card">
          <h3>企业资料</h3>
          <ul>
            <li>企业认证、发票抬头、纸电票邮寄状态实时同步</li>
            <li>多仓收货地址、员工账号一键授权</li>
            <li>安全策略覆盖设备指纹、操作留痕与审核日志</li>
          </ul>
        </article>
        <article class="preview-card">
          <h3>通知与积分</h3>
          <ul>
            <li>核实、支付、物流等事件实时推送，支持桌面通知</li>
            <li>购物车积分兑换与工厂聚乐部活动统一入口</li>
            <li>结算待办、开票申请、财务对账一站式处理</li>
          </ul>
        </article>
      </div>
      <div class="home__preview-actions">
        <button class="btn btn--primary" @click="goMemberCenter">进入会员中心</button>
        <button class="btn btn--ghost" @click="goOrders">查看我的订单</button>
      </div>
    </section>
    <WorkflowSection />
  </div>
</template>

<script setup>
import { computed, inject, reactive, ref, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import HeroBanner from "../components/HeroBanner.vue";
import SearchFilters from "../components/SearchFilters.vue";
import ProductList from "../components/ProductList.vue";
import WorkflowSection from "../components/WorkflowSection.vue";
import { products as fallbackProducts, ads } from "../data/products";
import { useCatalogStore } from "../store/catalog";
import { useUserStore } from "../store/user";
import { useCartStore } from "../store/cart";
import { useVerificationStore } from "../store/verification";
import { message } from "../utils/message";

const router = useRouter();
const appBridge = inject("appBridge", null);

const userStore = useUserStore();
const catalogStore = useCatalogStore();
const cartStore = useCartStore();
const verificationStore = useVerificationStore();

const {
  list,
  loading: catalogLoading,
  error: catalogError,
  total: catalogTotal,
  brandOptions: dynamicBrands,
  originOptions: dynamicOrigins,
  warehouseOptions: dynamicWarehouses
} = storeToRefs(catalogStore);

const isLoggedIn = computed(() => userStore.isLoggedIn);

const filters = reactive({
  model: "",
  brand: "",
  origin: "",
  warehouse: ""
});

const pagination = reactive({
  page: 1,
  pageSize: 12
});

const fallbackBrandOptions = [...new Set(fallbackProducts.map(item => item.brand))];
const fallbackOriginOptions = [...new Set(fallbackProducts.map(item => item.origin))];
const fallbackWarehouseOptions = [
  ...new Set(fallbackProducts.map(item => item.warehouse))
];

const brandOptions = computed(() =>
  dynamicBrands.value.length ? dynamicBrands.value : fallbackBrandOptions
);
const originOptions = computed(() =>
  dynamicOrigins.value.length ? dynamicOrigins.value : fallbackOriginOptions
);
const warehouseOptions = computed(() =>
  dynamicWarehouses.value.length
    ? dynamicWarehouses.value
    : fallbackWarehouseOptions
);

const products = computed(() => list.value);

const loadProducts = async () => {
  const keyword = filters.model || filters.brand;
  const params = {
    page: pagination.page,
    page_size: pagination.pageSize,
    keyword,
    brand: filters.brand,
    origin: filters.origin,
    warehouse: filters.warehouse
  };
  try {
    await catalogStore.loadList(params);
  } catch {
    /* store 内已有错误处理 */
  }
};

const handleSearch = () => {
  pagination.page = 1;
  loadProducts();
};

const handleReset = () => {
  filters.model = "";
  filters.brand = "";
  filters.origin = "";
  filters.warehouse = "";
  pagination.page = 1;
  loadProducts();
};

const handleRetry = () => {
  loadProducts();
};

const handlePageChange = page => {
  pagination.page = page;
  loadProducts();
};

const ensureLogin = () => {
  if (isLoggedIn.value) return true;
  if (userStore.partial) {
    router.push({ name: "member" });
    return false;
  }
  appBridge?.openLogin?.();
  return false;
};

const handleVerifyStock = async product => {
  if (!ensureLogin()) return;
  try {
    await catalogStore.requestVerify(product, 1);
    message.success("已发起库存核实，结果将通过消息通知您");
    await verificationStore.load({ page: 1, page_size: 10 }).catch(() => {});
  } catch (error) {
    message.error(error.message || "发起核实失败");
  }
};

const handleAddToCart = async product => {
  if (!ensureLogin()) return;
  try {
    await catalogStore.addCart(product, 1);
    message.success("已加入购物车，可前往购物车发起核实或下单");
    await cartStore.load().catch(() => {});
  } catch (error) {
    message.error(error.message || "加入购物车失败");
  }
};

const openLogin = () => {
  appBridge?.openLogin?.();
};

const scrollToSearch = () => {
  document.getElementById("search")?.scrollIntoView({ behavior: "smooth" });
};

const scrollToWorkflow = () => {
  document.getElementById("solutions")?.scrollIntoView({ behavior: "smooth" });
};

const goMemberCenter = () => {
  if (!ensureLogin()) return;
  router.push({ name: "member" });
};

const goOrders = () => {
  if (!ensureLogin()) return;
  router.push({ name: "orders" });
};

onMounted(() => {
  loadProducts();
});
</script>

<style scoped lang="scss">
.home {
  display: flex;
  flex-direction: column;
  gap: 32px;
  padding-bottom: 48px;
}

.home__member-preview {
  padding: 32px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.home__preview-header {
  display: flex;
  flex-direction: column;
  gap: 8px;

  h2 {
    margin: 0;
  }

  p {
    margin: 0;
    color: var(--gray-600);
  }
}

.home__preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 18px;
}

.preview-card {
  padding: 24px;
  border-radius: 16px;
  background: linear-gradient(140deg, #f6f8fc 0%, #ffffff 100%);
  border: 1px solid var(--gray-100);
  display: flex;
  flex-direction: column;
  gap: 12px;

  h3 {
    margin: 0;
  }

  ul {
    margin: 0;
    padding-left: 18px;
    color: var(--gray-700);
    font-size: 13px;

    li + li {
      margin-top: 6px;
    }
  }
}

.home__preview-actions {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.btn {
  border: none;
  border-radius: 12px;
  padding: 12px 22px;
  font-weight: 600;
  cursor: pointer;

  &--primary {
    background: var(--primary-color);
    color: #fff;

    &:hover {
      background: #0040ad;
    }
  }

  &--ghost {
    background: var(--gray-100);
    color: var(--primary-color);
    border: 1px solid transparent;

    &:hover {
      border-color: var(--primary-color);
      background: #fff;
    }
  }
}
</style>
